package com.weavernorth.sysap.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.weavernorth.sysap.bean.SyncLog;
import com.weavernorth.sysap.dao.SyncOrgStrucDao;
import com.weavernorth.sysap.dao.SyncOrgStrucDaoImpl;
import com.alibaba.fastjson.JSONObject;

import com.weavernorth.util.Logger4jUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.company.SubCompanyComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.resource.ResourceComInfo;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 同步组织架构工具类
 *
 * @author XvFei
 * @version v1.0 created by 2019-06-12
 */
public class SyncUtil extends BaseBean {

//    public static Log log = LogFactory.getLog(SyncUtil.class.getName());

    /**
     * @param syncDataUrl 要同步的哪个数据的url（集团、分部、部门、岗位、人员）
     * @return 获取到的同步数据
     * @description 通过接口，获取到要同步的数据信息
     */
    public JSONArray getSyncDataInfos(Logger log,String syncDataUrl, String requestXml) {

        /************************1.创建变量、并对变量初始化和赋值************************/
        //获取的要同步的数据
        JSONArray jsonArray = new JSONArray();
        CommonToSapUtil commonToSapUtil = new CommonToSapUtil();
         log.info("同步xml==" + requestXml);

        try {

            /************************2.接口请求调用，获取返回数据************************/
            String resultStr = commonToSapUtil.sendPost(syncDataUrl, requestXml.toString(), "utf-8");
            log.info("返回xml==" + resultStr);
            /************************3.数据处理************************/
            //xmlStr为上图格式的字符串
            Document document = null;
            try {
                document = DocumentHelper.parseText(resultStr);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            if (document.selectSingleNode("//IT_DATA_JSON") != null) {
                String returnSubcom = Util.null2String(document.selectSingleNode("//IT_DATA_JSON").getText());
                  log.info("returnSubcom结果=" + returnSubcom);
                if (!"".equals(returnSubcom)) {
                    jsonArray = JSON.parseArray(returnSubcom);
                    log.info("返回数组" + jsonArray.toString());
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            log.info("请求同步组织（分部、部门）接口时报错，错误原因：" + e.getMessage());
            jsonArray = null;
        }finally {
            /************************4.数据返回************************/
            return jsonArray;
        }


    }


    /**
     * @param syncDataUrl 要同步的哪个数据的url（集团、分部、部门、岗位、人员）
     * @return 获取到的同步数据
     * @description 通过接口，获取到要同步的数据信息
     */
    public JSONObject getSyncResourceDataInfos(Logger log,String syncDataUrl, String requestXml) {
        log.info("得到人员数据");

        /************************1.创建变量、并对变量初始化和赋值************************/
        //返回值
        JSONObject jsonObject = new JSONObject();
        //获取的要同步的主账号数据
        JSONArray jsonArray = new JSONArray();
        //获取的要同步的次账号数据
        JSONArray jsonSecondArray = new JSONArray();
        CommonToSapUtil commonToSapUtil = new CommonToSapUtil();
        // log.info("同步xml==" + requestXml);
        try {

            /************************2.接口请求调用，获取返回数据************************/
            String resultStr = commonToSapUtil.sendPost(syncDataUrl, requestXml.toString(), "utf-8");
             log.info("返回xml==" + resultStr);
            /************************3.数据处理************************/
            //xmlStr为上图格式的字符串
            Document document = null;
            try {
                document = DocumentHelper.parseText(resultStr);
                log.info("字符串转为document对象！");
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            if (document.selectSingleNode("//IT_DATA_JSON") != null) {
                String returnSubcom = Util.null2String(document.selectSingleNode("//IT_DATA_JSON").getText());
                log.info("人员数据json数组:" + returnSubcom);
                if (!"".equals(returnSubcom)) {
                    jsonArray = JSON.parseArray(returnSubcom);
                    jsonObject.put("mainJob", jsonArray);

                }
            }
            if (document.selectSingleNode("//IT_DATA_FG_JSON") != null) {
                String returnSubSecondcom = Util.null2String(document.selectSingleNode("//IT_DATA_FG_JSON").getText());
//                   log.info("次账号信息json数组:" + returnSubSecondcom);
                if (!"".equals(returnSubSecondcom)) {
                    jsonSecondArray = JSON.parseArray(returnSubSecondcom);
                    jsonObject.put("secondJob", jsonSecondArray);
                    //log.info("返回数组" + jsonArray.toString());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("同步接口转换数据报错，错误原因：" + e.getMessage());
            jsonObject = null;
        }finally {
            /************************4.数据返回************************/
            return jsonObject;
        }
    }


    /**
     * 字符串去重
     *
     * @param stringStr
     * @return
     */
    public static String removeDuplicate(Logger log,String stringStr) {
        String returnValue = "";
        List list = null;
        try {
            list = new ArrayList();
            if (!"".equals(stringStr)) {
                String[] strArray = stringStr.split(",");
                for (int i = 0; i < strArray.length; i++) {
                    String str = Util.null2String(strArray[i]);
                    if (!"".equals(str)) {
                        list.add(str);
                    }
                }

                HashSet h = new HashSet(list);
                list.clear();
                list.addAll(h);

                StringBuffer sb = new StringBuffer();
                for (int j = 0; j < list.size(); j++) {
                    sb.append("," + list.get(j) + ",");
                }
                returnValue = replaceStr(sb.toString()) + ",";
            }
        } catch (Exception e) {
            log.error("删除直接上级重复数据失败！" + e);
        }
        return returnValue;
    }

    public static String replaceStr(String str) {
        ArrayList list = Util.TokenizerString(str, ",");
        String temp = "";
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                if (temp.equals("")) {
                    temp = (String) list.get(i);
                } else {
                    temp += "," + (String) list.get(i);
                }
            }
        }
        return temp;
    }

    /**
     * 性别转换类
     *
     * @param str 1男 2女
     * @return 0男 1女
     */
    public static String transformSex(String str) {
        String sex = "";
        if ("".equals(str)) {
            return sex;

        } else if ("1".equals(str)) {

            sex = "0";

        } else if ("2".equals(str)) {

            sex = "1";
        }

        return sex;
    }

    /**
     * 人员状态类
     *
     * @param str 3：在职:0,1,2：离职
     * @return 0：试用 1：正式 2：临时 3：试用延期 4：解聘 5：离职 6：退休 7：无效
     */
    public static int transformStatus(String str) {
        int status = 7;
        if ("".equals(str)) {
            return status;
        } else if ("0".equals(str) || "1".equals(str) || "2".equals(str)) {

            status = 5;

        } else if ("3".equals(str)) {

            status = 1;
        }

        return status;
    }


    /*
     *获取同步hr的xml
     *
     */

    public String getOrgXml(Logger log,String xmlPart, List<JSONObject> dataList, String isall) {
        log.info("同步的xml类型:" + xmlPart);
        StringBuffer strRequestXml = new StringBuffer();
        //org返回组织即分部xml请求
        if ("org".equals(xmlPart) || "department".equals(xmlPart)) {
            strRequestXml.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:sap-com:document:sap:rfc:functions'>");
            strRequestXml.append("<soapenv:Header/>");
            strRequestXml.append("<soapenv:Body>");
            strRequestXml.append("<urn:ZIF_FW_001>");
            strRequestXml.append("<E_SENDR></E_SENDR>");
            //是否全量 IS_ALL 是否全量 必填-Y全量,N增量
            if ("0".equals(isall)) {
                strRequestXml.append("<IS_ALL>Y</IS_ALL>");
            } else {
                strRequestXml.append("<IS_ALL>N</IS_ALL>");
            }
            //是否泛微,默认值X
            strRequestXml.append("<IS_FW>X</IS_FW>");
            strRequestXml.append("<I_MSGID></I_MSGID>");
            strRequestXml.append("<IT_DATA>");

            if (dataList != null && dataList.size() > 0) {
                for (int index = 0; index < dataList.size(); index++) {
                    JSONObject jsonData = dataList.get(index);
                    strRequestXml.append("<item>");
                    strRequestXml.append("<OBJID>" + jsonData.get("objid") + "</OBJID>");
                    strRequestXml.append("<IFFLG>" + jsonData.get("ifflg") + "</IFFLG>");
                    strRequestXml.append("<IFMSG>" + jsonData.get("ifmsg") + "</IFMSG>");
                    strRequestXml.append("</item>");
                }
            }
            strRequestXml.append("</IT_DATA>");
            strRequestXml.append("<IT_DATA_JSON></IT_DATA_JSON>");
            strRequestXml.append("</urn:ZIF_FW_001>");
            strRequestXml.append("</soapenv:Body>");
            strRequestXml.append("</soapenv:Envelope>");
        }

        //岗位请求xml
        else if ("jobtitles".equals(xmlPart)) {
            strRequestXml.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:sap-com:document:sap:rfc:functions'>");
            strRequestXml.append("<soapenv:Header/>");
            strRequestXml.append("<soapenv:Body>");
            strRequestXml.append("<urn:ZIF_FW_002>");
            strRequestXml.append("<IT_DATA_JSON></IT_DATA_JSON>");
            strRequestXml.append("<E_SENDR></E_SENDR>");
            //是否全量 IS_ALL 是否全量 必填-Y全量,N增量
            if ("0".equals(isall)) {
                strRequestXml.append("<IS_ALL>Y</IS_ALL>");
            } else {
                strRequestXml.append("<IS_ALL>N</IS_ALL>");
            }
            //是否泛微,默认值X
            strRequestXml.append("<IS_FW>X</IS_FW>");
            strRequestXml.append("<I_MSGID></I_MSGID>");
            strRequestXml.append("<IT_DATA>");
            if (dataList != null && dataList.size() > 0) {
                for (int index = 0; index < dataList.size(); index++) {
                    JSONObject jsonData = dataList.get(index);
                    strRequestXml.append("<item>");
                    strRequestXml.append("<OBJID>" + jsonData.get("objid") + "</OBJID>");
                    strRequestXml.append("<IFFLG>" + jsonData.get("ifflg") + "</IFFLG>");
                    strRequestXml.append("<IFMSG>" + jsonData.get("ifmsg") + "</IFMSG>");
                    strRequestXml.append("</item>");
                }
            }
            strRequestXml.append("</IT_DATA>");
            strRequestXml.append("</urn:ZIF_FW_002>");
            strRequestXml.append("</soapenv:Body>");
            strRequestXml.append("</soapenv:Envelope>");
        }
        //人员请求xml
        else if ("resourceInfo".equals(xmlPart)) {
            strRequestXml.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:sap-com:document:sap:rfc:functions'>");
            strRequestXml.append("<soapenv:Header/>");
            strRequestXml.append("<soapenv:Body>");
            strRequestXml.append("<urn:ZIF_FW_003>");
            strRequestXml.append("<E_SENDR></E_SENDR>");
            //是否全量 IS_ALL 是否全量 必填-Y全量,N增量
            //是否全量 IS_ALL 是否全量 必填-Y全量,N增量
            if ("0".equals(isall)) {
                strRequestXml.append("<IS_ALL>Y</IS_ALL>");
            } else {
                strRequestXml.append("<IS_ALL>N</IS_ALL>");
            }
            //是否泛微,默认值X
            strRequestXml.append("<IS_FW>X</IS_FW>");
            strRequestXml.append("<IT_DATA>");
            if (dataList != null && dataList.size() > 0) {
                for (int index = 0; index < dataList.size(); index++) {
                    JSONObject jsonData = dataList.get(index);
                    strRequestXml.append("<item>");
                    strRequestXml.append("<PERNR>" + jsonData.get("workcode") + "</PERNR>");
                    strRequestXml.append("<IFFLG>" + jsonData.get("ifflg") + "</IFFLG>");
                    strRequestXml.append("<IFMSG>" + jsonData.get("ifmsg") + "</IFMSG>");
                    strRequestXml.append("</item>");
                }
            }
            strRequestXml.append("</IT_DATA>");
            strRequestXml.append("<IT_DATA_FG_JSON></IT_DATA_FG_JSON>");
            strRequestXml.append("<IT_DATA_JSON></IT_DATA_JSON>");
            strRequestXml.append("<I_MSGID></I_MSGID>");
            strRequestXml.append("</urn:ZIF_FW_003>");
            strRequestXml.append("</soapenv:Body>");
            strRequestXml.append("</soapenv:Envelope>");
        }

        return strRequestXml.toString();
    }

    /**
     * 清空缓存
     *
     * @param type 同步类型
     */
    public void clearCache(int type) {
        try {
            switch (type) {
                case 0:
                    SubCompanyComInfo sc = new SubCompanyComInfo();
                    sc.removeCompanyCache();
                    break;
                case 1:
                    SubCompanyComInfo sc1 = new SubCompanyComInfo();
                    sc1.removeCompanyCache();
                    DepartmentComInfo dc = new DepartmentComInfo();
                    dc.removeCompanyCache();
                    break;
                case 2:
                    JobTitlesComInfo jc = new JobTitlesComInfo();
                    jc.removeJobTitlesCache();
                    SubCompanyComInfo sc2 = new SubCompanyComInfo();
                    sc2.removeCompanyCache();
                    DepartmentComInfo dc1 = new DepartmentComInfo();
                    dc1.removeCompanyCache();
                    break;
                case 3:
                    ResourceComInfo rc = new ResourceComInfo();
                    rc.removeResourceCache();
                    break;
                default:
                    break;
            }

        } catch (Exception e) {
            this.writeLog("清空缓存失败:" + e);
        }

    }


    /**
     * 根据组织类型拆分组织数据
     *
     * @param dataArray 组织数据
     * @param orgType   组织类型：Y：分部；N：部门
     * @return 根据orgType拆分好的数据
     */
    public JSONObject splitSubcompanyAndDepartmentData(Logger log,JSONArray dataArray, String orgType) {
        //log.info("传入数据" + dataArray.toString());
        //返回json数组
        JSONArray jsonSubcomArray = new JSONArray();
        JSONArray jsonDepartmentArray = new JSONArray();
        JSONObject jsonOrg = new JSONObject();
        //数组不为空
        if (dataArray != null && dataArray.size() > 0) {
            //循环组织数据
            for (int index = 0; index < dataArray.size(); index++) {
                //组织类
                JSONObject dataJSON = JSON.parseObject(String.valueOf(dataArray.get(index)));
                //区分组织和部门
                String orgTypeObj = Util.null2String(dataJSON.get("is_fb"));
                //log.info("是否为分部" + orgTypeObj);
                if (!"".equals(orgTypeObj)) {
                    if (orgType.equals(orgTypeObj)) {
                        jsonSubcomArray.add(dataJSON);
                    } else {
                        jsonDepartmentArray.add(dataJSON);
                    }
                } else {
                    log.info("orgCode:" + dataJSON.get("objid") + ",orgName:" + dataJSON.get("stext") +
                            "该条记录的组织类型无法判别。");
                    continue;
                }
            }

            //返回前根据组织级别升序排序
            jsonSubcomArray = JSON.parseArray(jsonArraySort(log,jsonSubcomArray));
            jsonDepartmentArray = JSON.parseArray(jsonArraySort(log,jsonDepartmentArray));

        } else {
            jsonSubcomArray = null;
            jsonDepartmentArray = null;
        }
        jsonOrg.put("subcompany", jsonSubcomArray);
        jsonOrg.put("department", jsonDepartmentArray);

        return jsonOrg;
    }


    /**
     * 按照JSONArray中的对象的某个字段进行排序(采用fastJson)
     *
     * @param jsonArr json数组字符串
     */
    public static String jsonArraySort(Logger log,JSONArray jsonArr) {
        //log.info("进入排序" + jsonArr.toString());
        JSONArray sortedJsonArray = new JSONArray();
        List<JSONObject> jsonValues = new ArrayList<JSONObject>();
        for (int i = 0; i < jsonArr.size(); i++) {
            jsonValues.add(jsonArr.getJSONObject(i));
        }
        Collections.sort(jsonValues, new Comparator<JSONObject>() {
            private static final String KEY_NAME = "zjb";

            @Override
            public int compare(JSONObject jsonBegin, JSONObject jsonEnd) {
                String valA = new String();
                String valB = new String();
                try {
                    // 这里是a、b需要处理的业务，需要根据你的规则进行修改。
                    valA = jsonBegin.getString(KEY_NAME);
                    valB = jsonEnd.getString(KEY_NAME);
                } catch (JSONException e) {
                }
                return valA.compareTo(valB);
            }
        });
        for (int i = 0; i < jsonArr.size(); i++) {
            sortedJsonArray.add(jsonValues.get(i));
        }
        // log.info("排序返回结果" + sortedJsonArray.toString());
        return sortedJsonArray.toString();
    }


    /**
     * 回写同步的数据
     *
     * @param intSyncType   同步类型
     * @param writeBackData 回写的数据
     * @return 回写是否成功
     */
    public boolean writeBackSyncInfo(Logger log,int intSyncType, List<JSONObject> writeBackData, String isall) {

        boolean returnStatus = false;
        //1.获取回写数据的请求接口url "
        String strWriteBackUrl = "";
        //同步类型标识
        String strSyncType = "";
        //0为组织类型,获取组织的请求路径
        if (intSyncType == 0) {
            strWriteBackUrl = Util.null2String(this.getPropValue("sapMess", "syncorginfourl"));
            strSyncType = "org";
        }
        //1为岗位,获取岗位的请求路径
        else if (intSyncType == 1) {
            strWriteBackUrl = Util.null2String(this.getPropValue("sapMess", "syncJobtitleUrl"));
            strSyncType = "jobtitles";
        }
        //2为人员同步
        else if (intSyncType == 2) {
            strWriteBackUrl = Util.null2String(this.getPropValue("sapMess", "syncResourceUrl"));
            strSyncType = "resourceInfo";
        }
        log.info("回写调用接口路径" + strWriteBackUrl);
        //2.回写数据
        String strBackXml = getOrgXml(log,strSyncType, writeBackData, isall);
        //log.info("回写调用的xml" + strBackXml);

        //log.info("回写数据的请求参数：" + writeBackData);
        try {
            //3.接口请求调用，获取返回数据
            JSONArray resultStr = getSyncDataInfos(log,strWriteBackUrl, strBackXml);
            if (resultStr != null && resultStr.size() > 0) {
                returnStatus = true;
            } else {
                returnStatus = false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("回写同步数据失败，错误原因：" + e.getMessage());
            returnStatus = false;
        }

        return returnStatus;
    }


    /**
     * @param tablename 建模表单名称
     * @return 建模表单模块id
     * @ToDo 通过建模表单获取建模莫模块id
     */
    public String getModeIdBytableName(String tablename) {
        RecordSet rsRecordSet = new RecordSet();
        String result = "1";
        //查询表单建模模块id
        String selectSql = "select id from modeinfo where formid=(select id from workflow_bill " +
                "where tablename='" + tablename + "') and isdelete !=1";
        rsRecordSet.execute(selectSql);
        if (rsRecordSet.next()) {
            //已经存在
            result = rsRecordSet.getString("id");
        }
        return result;
    }

    /**
     * 给建模表授权
     */

    public void empowerForm(Logger log,String strUuid, String strTable, String strFormid) {

        //给插入数据授权
        RecordSet rs2 = new RecordSet();
        //查询表单建模的id
        rs2.execute("select id  from " + strTable + " where uuid='" + strUuid + "'");
        while (rs2.next()) {
            int intBillid = rs2.getInt("id");
            log.info("得到的表单id" + intBillid);
            //表单建模授权
            log.info("授权开始");
            ModeRightInfo modeRightInfoBanc = new ModeRightInfo();
            modeRightInfoBanc.setNewRight(true);
            modeRightInfoBanc.editModeDataShare(1, Integer.parseInt(strFormid), intBillid);
            log.info("授权结束");
        }

    }


    /**
     * 处理次账号
     *
     * @param jsonArraySecond 次账号数据
     */

    public void dealSecond(Logger log,JSONArray jsonArraySecond) {
        log.info("进入次账号处理");
        //数据库操作
        RecordSet rs = new RecordSet();
        RecordSet rsUp = new RecordSet();
        RecordSet rsSelect = new RecordSet();
        //查询部门id
        GetUserMessageUtil getUserMessageUtil = new GetUserMessageUtil();
        //数据库操作类
        SyncOrgStrucDao sosDao = new SyncOrgStrucDaoImpl();
        //日志类
//        SyncLog syncLog = new SyncLog();
        //存放所有有副岗的人员的编号
        List<String> list_deals=new ArrayList<>();
        //循环得有次账号的人员
        for (int i = 0; i < jsonArraySecond.size(); i++) {
            JSONObject jsonObject = jsonArraySecond.getJSONObject(i);
            //人员编码
            String strWorkcode = Util.null2String(jsonObject.get("pernr"));
            //岗位编码
            String strJobcode = Util.null2String(jsonObject.get("objid_gw"));
            //查找岗位id
            String strJobtitleid = sosDao.getIdByCode("hrmjobtitles", strJobcode);
            //部门id
            String strDepartId = getUserMessageUtil.getDepartmentId(strJobtitleid, rs);
            //分部id
            String strSubid = getUserMessageUtil.getSubid(strDepartId, rs);
            //部门编码
            String strDepart = Util.null2String(jsonObject.get("objid"));
            //主次账号区分 1为次账号
            String strMainSecond = Util.null2String(jsonObject.get("zhufugang"));
            //人员姓名
            String strLastname = Util.null2String(jsonObject.get("fg_name"));
            strLastname = (strLastname.replaceAll(" ", ""));
            log.info("账号标识:" + strMainSecond);
            rsSelect.execute("select id,loginid from hrmresource where workcode='" + strWorkcode + "' and (accounttype!=1 or accounttype is null)");
            rsSelect.next();

            //主账号id
            String strUserid = Util.null2String(rsSelect.getString("id"));
            //登录账号
            String strLoginid = Util.null2String(rsSelect.getString("loginid"));
            //如果为主账号,则把此账号的所有次账号失效
            if ("".equals(strMainSecond)) {
                String upSql = "update hrmresource set status='5' where workcode=? and accounttype=1";
                log.info("更新次账号为离职:" + upSql + ",workcode:" + strWorkcode);
                rs.executeUpdate(upSql, strWorkcode);
                //需要将主账号的信息更新到给次账号
            }
            //如果为次账号,则判断是否有,有则开启,无则插入
            if ("1".equals(strMainSecond)) {
                String sql = "select id from hrmresource where workcode=? and accounttype=1 and jobtitle=?";
                rs.executeQuery(sql, strWorkcode, strJobtitleid);
                //有则开启
                if (rs.next()) {
                    String strSecondId = Util.null2String(rs.getString("id"));
                    String upSql = "update hrmresource set status='1',loginid=?,lastname=?,departmentid=?,subcompanyid1=?,belongto=?,accounttype='1' where workcode=? and accounttype=1 and jobtitle=?";
                    log.info("更新次账号为生效:" + upSql + ",workcode:" + strWorkcode + ";次账户id:" + strSecondId);

                    boolean flag = rsUp.executeUpdate(upSql, strLoginid + "_" + strSecondId, strLastname, strDepartId, strSubid, strUserid, strWorkcode, strJobtitleid);

                    if (flag) {
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_SUCCESS);
//                        syncLog.setSyncInfoDesc("人员同步成功");
                        log.info("人员同步成功");
                    } else {
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                        syncLog.setSyncInfoDesc("人员编号为:" + strWorkcode + ",岗位id为:" + strJobtitleid + ",人员同步失败");
                        log.info("人员编号为:" + strWorkcode + ",岗位id为:" + strJobtitleid + ",人员同步失败");
                    }
                }
                //否则插入
                else {
                    //最大id
                    int intMaxid = sosDao.getHrmMaxid();
                    String insertSql = "insert into hrmresource(id,loginid,lastname,workcode,status,accounttype,jobtitle,departmentid,subcompanyid1,belongto) values(?,?,?,?,?,?,?,?,?,?)";
                    log.info("插入次账号信息:" + insertSql + ",workcode:" + strWorkcode);
                    boolean flag = rsUp.executeUpdate(insertSql, intMaxid, strLoginid +"_"+ intMaxid, strLastname, strWorkcode, "1", "1", strJobtitleid, strDepartId, strSubid, strUserid);
                    if (flag) {
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_SUCCESS);
//                        syncLog.setSyncInfoDesc("人员同步成功");
                        log.info("人员同步成功");
                    } else {
//                        syncLog.setSyncInfoType(CommonConstant.SYNC_RESULT_DEFULT);
//                        syncLog.setSyncInfoDesc("人员编号为:" + strWorkcode + ",岗位id为:" + strJobtitleid + ",人员同步失败");
                        log.info("人员编号为:" + strWorkcode + ",岗位id为:" + strJobtitleid + ",人员同步失败");
                    }
                }


            }

//            syncLog.setSyncType(CommonConstant.SYNC_TYPE_RESOURCE);
//            syncLog.setSyncDate(CommonToSapUtil.getCurDate());
//            syncLog.setSyncTime(CommonToSapUtil.getCurTime());
//            syncLog.setSyncCode(strWorkcode);
//            syncLog.setSyncName(strLastname);
//            //日志插入
//            sosDao.insertSyncLog(syncLog);

            list_deals.add("'"+strWorkcode+"'");

        }
        if(list_deals.size()>0){
            log.info("SAP传入的副岗人员："+list_deals.toString());
            StringBuilder sb_deals=new StringBuilder();
            List<String> collect = list_deals.stream().distinct().collect(Collectors.toList());
            log.info("SAP传入的去重后的副岗人员："+collect.toString());
            //SAP传入的副岗人员
            String str_fgry=String.join(",",collect);
            String update_Sql = "update hrmresource set status='5' where workcode not in("+str_fgry+") and accounttype=1";
            log.info("更新所有无次账号的人员次账号为离职:" + update_Sql);
            rs.executeUpdate(update_Sql);
        }


    }


}
